package com.smile.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.smile.commons.Result;
import com.smile.commons.request.RequestIdUtils;
import com.smile.mapper.AirportInfoMapper;
import com.smile.mapper.InspectionTaskMapper;
import com.smile.model.domain.FeisuanAirportInfo;
import com.smile.model.domain.FeisuanInspectionTask;
import com.smile.model.dto.request.*;
import com.smile.service.mqtt.handler.AbstractServicesHandler;
import com.smile.service.AirlineService;
import com.smile.service.entity.services.BaseServicesEntity;
import com.smile.service.entity.services.InFlightWaylineDeliver;
import com.smile.service.task.FlyServicesExecutor;
import com.smile.service.task.LiveServicesExecutor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.dynamictp.core.executor.DtpExecutor;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class AirlineServiceImpl implements AirlineService {


    @Autowired
    private AbstractServicesHandler abstractServicesHandler;

    @Autowired
    private DtpExecutor dtpExecutor0;

    @Autowired
    private AirportInfoMapper airportInfoMapper;

    @Autowired
    private InspectionTaskMapper inspectionTaskMapper;

    public Result stopTask(ExecuteAirlineTaskRequestDTO executeAirlineTaskRequestDTO) throws Exception {
        Result result = new Result();
        log.info("执行下发航线任务,requestId={}", RequestIdUtils.get());
        try {
//            FlyServicesExecutor.create()
//
//                    .flightId(executeAirlineTaskRequestDTO.getFlightId())
//                    .flightTaskPrepare(executeAirlineTaskRequestDTO.getAirlineUrl(),
//                            executeAirlineTaskRequestDTO.getETag(), executeAirlineTaskRequestDTO.getGateway())
//                    .gateway(executeAirlineTaskRequestDTO.getGateway())
//                    .execute()
//            ;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
            result.setStatus(1);
            result.setMessage("指令发送成功");

        return result;
    }
    @Override
    public Result executeAirlineTask(ExecuteAirlineTaskRequestDTO executeAirlineTaskRequestDTO) throws Exception {
        Result result = new Result();
        log.info("执行下发航线任务,requestId={}", RequestIdUtils.get());

        QueryWrapper<FeisuanAirportInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("gateway_sn", executeAirlineTaskRequestDTO.getGateway());
        List<FeisuanAirportInfo> feisuanAirportInfos = airportInfoMapper.selectList(queryWrapper);
        String errorMsg = "";
        Integer errorCode = 0;
        if (CollectionUtil.isNotEmpty(feisuanAirportInfos)) {
            if (!(feisuanAirportInfos.get(0).getFlighttaskStepCode() == 0
                    || feisuanAirportInfos.get(0).getFlighttaskStepCode() == 5
                    || feisuanAirportInfos.get(0).getFlighttaskStepCode() == 2)) {
                result.setStatus(0);
                result.setMessage("机场正在执行其他任务");
                errorMsg = "机场正在执行其他任务";
                errorCode = 1;
//                return result;
            }
            if (feisuanAirportInfos.get(0).getModifyTime().plusMinutes(10).compareTo(LocalDateTime.now()) < 0) {
                result.setStatus(0);
                result.setMessage("机场离线");
                errorMsg = "机场离线";
                errorCode = 1;
//                return result;
            }
        }

        UpdateWrapper<FeisuanInspectionTask> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("flight_id", executeAirlineTaskRequestDTO.getFlightId());

        updateWrapper.set("bid", executeAirlineTaskRequestDTO.getBid());
        updateWrapper.set("tid", executeAirlineTaskRequestDTO.getTid());
        if (errorCode == 1) {
            updateWrapper.set("error_message", errorMsg);
            updateWrapper.set("error_code", 1);
            updateWrapper.set("status", 5);
        }else{
            updateWrapper.set("start_time", LocalDateTime.now());
        }
        inspectionTaskMapper.update(null, updateWrapper);
        if (errorCode == 0) {
            dtpExecutor0.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        FlyServicesExecutor.create()

                                .flightId(executeAirlineTaskRequestDTO.getFlightId())
                                .flightTaskPrepare(executeAirlineTaskRequestDTO.getAirlineUrl(),
                                        executeAirlineTaskRequestDTO.getETag(), executeAirlineTaskRequestDTO.getGateway())
                                .gateway(executeAirlineTaskRequestDTO.getGateway())
                                .execute()
                        ;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    //TODO 这里之后可以改成定时线程池
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    log.info("执行执行航线任务,requestId={}", RequestIdUtils.get());

                    try {
                        //        baseServicesEntity.setBid(UUID.randomUUID().toString());
//        baseServicesEntity.setTid(UUID.randomUUID().toString());
                        FlyServicesExecutor.create()
                                .bidAndTid(executeAirlineTaskRequestDTO.getBid(), executeAirlineTaskRequestDTO.getTid())
                                .flightId(executeAirlineTaskRequestDTO.getFlightId())
                                .flightTaskExecuteTask()
                                .gateway(executeAirlineTaskRequestDTO.getGateway())
                                .execute();
//                        inspectionTaskMapper.update(null, updateWrapper);
                    } catch (MqttException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            result.setStatus(1);
            result.setMessage("指令发送成功");
        }

        return result;
    }

    @Override
    public void inFlightWaylineDeliver(InFlightWaylineDeliverRequestDTO inFlightWaylineDeliverRequestDTO) throws MqttException {
        FlyServicesExecutor.create()
                .inFlightWaylineDeliver(inFlightWaylineDeliverRequestDTO.getEtag(), inFlightWaylineDeliverRequestDTO.getUrl(),
                        inFlightWaylineDeliverRequestDTO.getInFlightWaylineId())
                .gateway(inFlightWaylineDeliverRequestDTO.getGateway())
                .execute();
    }

    @Override
    public void flighttaskPause(FlighttaskPauseRequestDTO flighttaskPauseRequestDTO) throws MqttException {
        FlyServicesExecutor.create()
                .flighttaskPause()
                .gateway(flighttaskPauseRequestDTO.getGateway())
                .execute();
    }

    @Override
    public void flighttaskRecovery(FlighttaskPauseRequestDTO flighttaskPauseRequestDTO) throws MqttException {
        FlyServicesExecutor.create()
                .flighttaskRecovery()
                .gateway(flighttaskPauseRequestDTO.getGateway())
                .execute();
    }

    @Override
    public void inFlightWaylineStop(InFlightWaylineStopRequestDTO inFlightWaylineStopRequestDTO) throws MqttException {
        FlyServicesExecutor.create()
                .inFlightWaylineStop(inFlightWaylineStopRequestDTO.getInFlightWaylineId())
                .gateway(inFlightWaylineStopRequestDTO.getGateway())
                .execute();
    }

    @Override
    public void inFlightWaylineRecover(InFlightWaylineRecoverRequestDTO inFlightWaylineRecoverRequestDTO) throws MqttException {
        FlyServicesExecutor.create()
                .inFlightWaylineRecover(inFlightWaylineRecoverRequestDTO.getInFlightWaylineId())
                .gateway(inFlightWaylineRecoverRequestDTO.getGateway())
                .execute();
    }

    @Override
    public void inFlightWaylineCancel(InFlightWaylineDeliverRequestDTO inFlightWaylineDeliverRequestDTO) throws MqttException {
        FlyServicesExecutor.create()
                .inFlightWaylineCancel()
                .gateway(inFlightWaylineDeliverRequestDTO.getGateway())
                .execute();
    }

    @Override
    public void flyToPointStop(FlyToPointStopRequestDTO flyToPointStopRequestDTO) throws MqttException {

        log.info("执行停止飞往目标点任务,requestId={}", RequestIdUtils.get());

        FlyServicesExecutor.create()
                .flyToPointStop().gateway(flyToPointStopRequestDTO.getGateway())
                .execute();
    }


}
